package com.zyj.delayqueue.norely;

import lombok.Data;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 假设这个就是延时队列传输的内容
 */
@Data
public class DelayedTask implements Delayed {

    public static DelayedTask build(Duration delayedTime, Integer data) {
        DelayedTask delayedTask = new DelayedTask();
        delayedTask.data = data;
        delayedTask.triggerTime = Instant.now().plus(delayedTime);
        return delayedTask;
    }

    private Instant triggerTime;
    private Integer data;

    public long getDelay(TimeUnit unit) {
        //计算的时候别用纳秒, 会有问题, 到毫秒就OK了
        long nowMillis = Instant.now().toEpochMilli();
        long triggerTimeMillis = triggerTime.toEpochMilli();
        long delayedMillis = triggerTimeMillis - nowMillis;
        if (delayedMillis <= 0) {
            delayedMillis = 0;
        }
        return unit.convert(Duration.ofMillis(delayedMillis));
    }

    @Override
    public int compareTo(Delayed o) {
        return Long.compare(this.getDelay(TimeUnit.MILLISECONDS), o.getDelay(TimeUnit.MILLISECONDS));
    }
}
